package com.cup.common;

import java.util.Map;

import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class ExpressionUtils {

	private final static ExpressionParser PARSER = new SpelExpressionParser();

	public static String getVariableName(String expression) {
		return null;
	}

	@SuppressWarnings("unchecked")
	public static <T> T eval(String expression, Map<String, Object> variables) {
		StandardEvaluationContext context = new StandardEvaluationContext();
		context.setVariables(variables);
		for (String key : variables.keySet()) {
			expression = expression.replace(key, "#" + key);
		}
		Expression exp = PARSER.parseExpression(expression, new ElParserContext());
		return (T) exp.getValue(context);
	}

	@SuppressWarnings("unchecked")
	public static <T> T parse(String expression, Map<String, Object> variables) {
		StandardEvaluationContext context = new StandardEvaluationContext();
		context.setVariables(variables);
		Expression exp = PARSER.parseExpression(expression, new TemplateParserContext());
		return (T) exp.getValue(context);
	}

	public static class ElParserContext implements ParserContext {

		private final String expressionPrefix;

		private final String expressionSuffix;

		public ElParserContext() {
			this("${", "}");
		}

		public ElParserContext(String expressionPrefix, String expressionSuffix) {
			this.expressionPrefix = expressionPrefix;
			this.expressionSuffix = expressionSuffix;
		}

		@Override
		public final boolean isTemplate() {
			return true;
		}

		@Override
		public final String getExpressionPrefix() {
			return this.expressionPrefix;
		}

		@Override
		public final String getExpressionSuffix() {
			return this.expressionSuffix;
		}

	}

}
